<?php
// api/save.php
header('Content-Type: application/json');
require_once 'db.php';

try {
    // Get JSON input
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);

    if (!$data) {
        throw new Exception("Invalid JSON data received");
    }

    // Since this is a single-user tracker for now, we always update ID 1
    // In a multi-user app, you would use Session/Auth to determine the user ID
    $id = 1; 

    // Prepare statement (Upsert logic)
    if ($is_local) {
        // SQLite Upsert
        $stmt = $pdo->prepare("INSERT INTO progress (id, data, updated_at) VALUES (:id, :data, CURRENT_TIMESTAMP) 
                              ON CONFLICT(id) DO UPDATE SET data = :data, updated_at = CURRENT_TIMESTAMP");
    } else {
        // MySQL Upsert
        $stmt = $pdo->prepare("INSERT INTO progress (id, data, updated_at) VALUES (:id, :data, NOW()) 
                              ON DUPLICATE KEY UPDATE data = :data, updated_at = NOW()");
    }
    
    $stmt->execute([':id' => $id, ':data' => $json]);

    echo json_encode(['success' => true, 'message' => 'Progress saved successfully']);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
